<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Model\User;
use App\Http\Resources\UserResource;
use App\Http\Resources\UserCollection;
use App\Http\Requests\UserRequest;
use App\Repositories\User as objUser;
use Illuminate\Support\Collection;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;

class UserController extends Controller
{
    public function __construct(objUser $categoryRepositories)
    {
        parent::__construct($categoryRepositories);	
    }
    /**
     * 显示所有后台用户
     *
     * @return \Illuminate\Http\Response
     */
    public function home(Request $request)
    {
		$limit=$request->limit?$request->limit:10;
		
		$key=trim($request->get("key",''));
		
		$passed=$request->get("passed",-1);
		
		$sort=$request->get("sort",'id');
		
		$order=$request->get("order",'desc');
		
		if(!($sort=="id"||$sort=="last_at"||$sort=="login_times"||$sort=="created_at")){$sort="id";}
		
		if(!($order=="desc"||$order=="asc")){$order="desc";}

		$user=User::orderBy($sort,$order);
		
		if(isset($key)){
			$user=$user->where(function($query) use ($key){
                $query->where('phone', 'like','%'.$key.'%');
				$query->orWhere('name', 'like','%'.$key.'%');
            });
		}
		
		if(isset($passed)&&$passed!=-1){
			$user=$user->where('passed',$passed);
		}

		return $this->success(new UserCollection($user->paginate($limit)));
    }

    /**
     * 添加后台用户
     *
     * @return \Illuminate\Http\Response
     */
    public function store(UserRequest $request)
    {
	   $this->getRepositories()->store($request->all(),['form'=>['user'=>$request->user]]);
	   
	   return $this->success([],"保存用户成功");
    }
	
    /**
     * 删除后台用户
     *
     * @return \Illuminate\Http\Response
     */
    public function remove(Request $request)
    {
		$data = $request->all();
		
		$data= new Collection($data);
		
		if($data->contains($request->user('api')->id)){
			throw ValidationException::withMessages(["id" => "删除失败,你不能删除自己"]);
		}
		$this->getRepositories()->remove($request->all(),['form'=>['user'=>$request->user]]);
		
		return $this->success([],"删除用户成功");
    }
}
